<?php
/**
 * Created by PhpStorm.
 * User: cth
 * Date: 2017/6/13
 * Time: 上午10:13
 */

namespace App\Repositories;

use App\Models\Address;
use App\Models\WeixinUser;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use App\Http\Requests\AddressRequest;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class AddressRepository
{
    protected $address;

    public function __construct(Address $address)
    {
        $this->address = $address;
    }

    //我的地址
    public function getAllAddress($request)
    {
        //小程序
        $token = $request->token;
        if($token) {
            $WeixinUser = WeixinUser::where('token', $token)->first();
            if ($WeixinUser) {
                $user_id = $WeixinUser['user_id'];
            } else {
                return show(202, '用户不存在');
            }
        }else {
            $user_id = Auth::id();
            if (!$user_id) {
                return show(205, '未登录');
            }
        }
        $data = Address::where('user_id',$user_id)
            ->where('status',1)
            ->orderBy('pretermission','desc')
            ->orderBy('updated_at','desc')
            ->get();
        if($data->isEmpty())
        {
            return show('201','empty');
        }
        return show('200','ok',$data);
    }

    //详细地址
    public function getOneAddress($request)
    {
        $rules = [
            'id' => 'required|integer|exists:addresses,id',
        ];
        $message = [
            'id.*'=>'请选择的正确地址',
        ];
        $validator = Validator::make($request->all(), $rules,$message);
        if ($validator->fails()) {
            return show(202,$validator->errors()->first());
        }
        $id = $request->id;
        $data = Address::where('id',$id)->where('status',1)->first();
        if($data==null)
        {
            return show('201','empty');
        }
        return show('200','ok',$data);
    }

    //添加/修改地址
    public function addAddress(Request $request)
    {
        //小程序
        $token = $request->token;
        if($token) {
            $WeixinUser = WeixinUser::where('token', $token)->first();
            if ($WeixinUser) {
                $user_id = $WeixinUser['user_id'];
            } else {
                return show(202, '用户不存在');
            }
        }else {
            $user_id = Auth::id();
            if (!$user_id) {
               return redirect('/login');
            }
        }
        trY{
            $request = $request->all();
            if(isset($request['_token'])){
                unset($request['_token']);
            }
            if (isset($token)){
                unset($request['token']);
            }

            $request['user_id'] = $user_id;
            //检查有没有旧地址
            $address = Address::where('user_id',$user_id)->get();
            //第一个地址设置为默认地址
            if($address->isEmpty()){
                $request['pretermission']=1;
            }else{
                $request['pretermission']=0;
            }

            //插入/更新
            if(empty($request['id'])) {
                Address::create($request);
                $the_address_count = DB::table('addresses')->where('status',1)->where('user_id',$user_id)->count();
                // 如果只有一个地址，直接设置为默认即可
                if ($the_address_count==1){
                    DB::table('addresses')
                        ->where('status',1)
                        ->where('user_id',$user_id)
                        ->update(['pretermission'=>1]);
                    DB::commit();
                    return show('200','添加地址成功');
                }
                return show('200','添加地址成功');
            }else{
                try{
                    Address::where('id',$request['id'])->update($request);
                }catch (\Exception $exception){
                    dd($exception->getMessage());
                }

                return show('200','添加地址成功');
            }
        }catch (\Exception $e){
            //dd($e->getMessage());
            return show('200','添加地址失败');
        }

    }

    //设置默认地址
    public function defaultAddress($request)
    {
        $rules = [
            'id' => 'required|integer|exists:addresses,id',
            'token' => 'string',
        ];
        $message = [
            'id.*'=>'请选择的正确地址',
            'token.*'=>'请传递正确的令牌',
        ];
        $validator = Validator::make($request->all(), $rules,$message);
        if ($validator->fails()) {
            return show(202,$validator->errors()->first());
        }
        //小程序
        $token = $request->token;
        if($token) {
            $WeixinUser = WeixinUser::where('token', $token)->first();
            if ($WeixinUser) {
                $user_id = $WeixinUser['user_id'];
            } else {
                return show(202, '用户不存在');
            }
        }else {
            $user_id = Auth::id();
            if (!$user_id) {
                return show(205, '未登录');
            }
        }
        $id = $request->id;

        //把默认地址变非默认
        DB::beginTransaction();
        try{
            // 获取当前地址信息
            $now_address = DB::table('addresses')->where('status',1)->find($id);
            if ($now_address->pretermission == '1'){
                return show(201, '已经是默认地址');
            }

            $the_address_count = DB::table('addresses')->where('status',1)->where('user_id',$user_id)->count();
            // 如果只有一个地址，直接设置为默认即可
            if ($the_address_count=='1'){
                DB::table('addresses')
                    ->where('status',1)
                    ->where('user_id',$user_id)
                    ->update(['pretermission'=>1]);
                DB::commit();
                return show('200','修改成功');
            }

            $data1 = DB::table('addresses')
                ->where('pretermission',1)
                ->where('status',1)
                ->where('user_id',$user_id)
                ->update(['pretermission'=>0]);

            if ($the_address_count<2){
                $data2 = DB::table('addresses')
                    ->where('id',$id)
                    ->where('status',1)
                    ->where('user_id',$user_id)
                    ->update(['pretermission'=>1]);
                if($data1 && $data2) {
                    DB::commit();
                    return show(201, '已经是默认地址');
                }
            }else{

//        //改变默认地址
                $data2 = DB::table('addresses')
                    ->where('id',$id)
                    ->where('status',1)
                    ->where('user_id',$user_id)
                    ->update(['pretermission'=>1]);
            }
            if($data1 && $data2){
                DB::commit();
                return show('200','修改成功');
            }else{
                DB::rollBack();
                return show('201','修改失败');
            }
        }catch (\Exception $e){
//            dd($e->getMessage());
            DB::rollBack();
            return show('201','修改失败');
        }


    }

    //删除地址
    public function deleteAddresses($request)
    {
        /*
         * "SQLSTATE[42S02]: Base table or view not found: 1146 Table 'rzlt.Addresses' doesn't exist
         (SQL: update `Addresses` set `pretermission` = 1 where `user_id` = 2 order by `updated_at` desc limit 1)"
        */
        $rules = [
            'id' => 'required|integer|exists:addresses,id',
            'token' => 'string',
        ];
        $message = [
            'id.*'=>'请选择的正确地址',
            'token.*'=>'请传递正确的令牌',
        ];
        $validator = Validator::make($request->all(), $rules,$message);
        if ($validator->fails()) {
            return show(202,$validator->errors()->first());
        }
        //小程序
        $token = $request->token;
        if($token) {
            $WeixinUser = WeixinUser::where('token', $token)->first();
            if ($WeixinUser) {
                $user_id = $WeixinUser['user_id'];
            } else {
                return show(202, '用户不存在');
            }
        }else {
            $user_id = Auth::id();
            if (!$user_id) {
                return show(205, '未登录');
            }
        }
        try{
            $id = $request->id;
            $data = DB::table('addresses')->where('id',1252)->where('status',1)->first();
            $the_address_count = DB::table('addresses')->where('status',1)->where('user_id',$user_id)->count();

            DB::beginTransaction();
            // 如果只有一个地址，直接设置删除即可
            if ($the_address_count=='1'){
                DB::table('addresses')->where('id',$id)->update(['status'=>0,'deleted_at'=>date('Y-m-d H:i:s')]);
                DB::commit();
                return show('200','修改成功');
            }else{
                $delete = DB::table('addresses')->where('id',$id)->update(['status'=>0,'deleted_at'=>date('Y-m-d H:i:s')]);
                if($delete)
                {

                    $the_address = DB::table('addresses')->where('status',1)->where('user_id',$user_id)->get();
                    if (count($the_address)>1){
                        DB::table('addresses')
                            ->where('status',1)
                            ->where('user_id',$user_id)
                            ->update(['pretermission'=>1]);
                    }else{
                        $the_address2 = DB::table('addresses')->where('status',1)->where('user_id',$user_id)->get();
                        if($the_address2->isNotEmpty()){
                            $the_address2 = $the_address2->toArray();
                            $add_id = $the_address2[0]->id;
                        }
                        // 取顺位第一个地址伟默认地址   n
                        DB::table('addresses')
                            ->where('id',$add_id)
                            ->where('status',1)
                            ->where('user_id',$user_id)
                            ->limit(1)
                            ->update(['pretermission'=>1]);
                    }
                    DB::commit();
                    return show('200','删除成功');
                }
            }

        }catch (\Exception $e){
            DB::rollBack();
//            dd($e->getMessage());
            return show('201','删除失败');
        }
    }


}
